package org.itec.yeast.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.itec.yeast.db.DataManager;
import org.itec.yeast.trdo.TRYeastGene;
import org.itec.yeast.trdo.TRYeastGeneSQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 从文件SGD_features.tab中读取Yeast基因的信息。通过配置文件设置了"SGD_features.tab"文件的位置，
 * 并设置了需要提取的基因的Feature type。
 * @author GGCoke
 *
 */
public class YeastGeneFether {
	private static final Logger log = LoggerFactory.getLogger(YeastGeneFether.class);
	private static final String SEPARATER = "\t";
	private static final int FIELDS_IN_YEASTGENE = 16;
	private String PREFIX_PATH = "";
	private String DATA_FILEPATH = "";
	private String SELECTED_FEATURE_TYPE = "";
	
	public YeastGeneFether() throws URISyntaxException{
		super();
		getYeastProperties();
	}
	
	private void getYeastProperties() throws URISyntaxException{
		String fullPath = YeastGeneFether.class.getClassLoader().getResource("").toURI().getPath();
		PREFIX_PATH = fullPath.substring(0, fullPath.indexOf("WEB-INF/classes") - 1);
		ResourceBundle bundle = ResourceBundle.getBundle("yeast");
		DATA_FILEPATH = bundle.getString("SGD_Path");
		SELECTED_FEATURE_TYPE = bundle.getString("Feature_Type");
		if (DATA_FILEPATH.equals("") || SELECTED_FEATURE_TYPE.equals("")){
			log.error("Yeast数据信息配置错误，请检查yeast.properties文件!");
			return;
		}
	}
	
	private boolean isSelected(String type){
		String[] types = SELECTED_FEATURE_TYPE.replaceAll(" ", "").split(",");
		for (int i = 0; i < types.length; i++){
			if (type.equalsIgnoreCase(types[i])){
				return true;
			}
		}
		return false;
	}
	
	private TRYeastGene getYeastData(String[] contents){
		TRYeastGene yeast = new TRYeastGene(contents[0], contents[1]);
		yeast.setFeatureQualifier(contents[2]);
		yeast.setFeaturreName(contents[3]);
		yeast.setStandardName(contents[4]);
		yeast.setAlias(contents[5]);
		yeast.setParentFeatureName(contents[6]);
		yeast.setSecondSGDID(contents[7]);
		yeast.setChromosome(contents[8]);
		yeast.setStartCoordinate(Integer.parseInt(contents[9]));
		yeast.setStopCoordinate(Integer.parseInt(contents[10]));
		yeast.setStrand(contents[11]);
		yeast.setGeneticPosition(contents[12]);
		yeast.setCoordinateVersion(contents[13]);
		yeast.setSequenceVersion(contents[14]);
		
		// 有些Yeast没有description信息，因此需要判断该条记录是否有16个字段
		if (contents.length == FIELDS_IN_YEASTGENE){
			yeast.setDescciption(contents[15]);
		}
		
		return yeast;
	}
	
	public void fetchYeastData(){
		List<TRYeastGene> yeasts = new ArrayList<TRYeastGene>();
		TRYeastGeneSQL yeastSQL = new TRYeastGeneSQL();
		List<Map<String, String>> SGD_IDs = yeastSQL.getSGD_IDs();
		BufferedReader reader = null;
		
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(PREFIX_PATH + DATA_FILEPATH))));
			String line = null;
			
			while ((line = reader.readLine()) != null){
				String[] contents = line.split(SEPARATER);
				if (!isSelected(contents[1]))
					continue;
				Map<String, String> tmpYeast = new HashMap<String, String>();
				tmpYeast.put("Primary_SGDID", contents[0]);
				if (SGD_IDs.contains(tmpYeast))
					continue;
				TRYeastGene yeast = getYeastData(contents);
				yeasts.add(yeast);
				
				if (yeasts.size() >= 1000){
					yeastSQL.insert(yeasts);
					yeasts.clear();
				}
			}
			
			if (yeasts.size() != 0){
				yeastSQL.insert(yeasts);
				yeasts.clear();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("文件" + PREFIX_PATH + DATA_FILEPATH + "未找到");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("读取文件" + DATA_FILEPATH + "失败!");
		} finally {
			if (reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) throws URISyntaxException{
		YeastGeneFether fether = new YeastGeneFether();
		fether.fetchYeastData();
	}
}
